using Microsoft.Owin.Security;
using Newtonsoft.Json.Serialization;
using Sustainalytics.Auth.Common;
using Sustainalytics.Entities;
using Sustainalytics.Entities.ESGRatings;
using Sustainalytics.ESGRatings.BusinessLogic.Exceptions;
using System;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace Sustainalytics.ESGRatings.Tasks.HttpClients
{
    public class ESGCompanyReportClient : HttpClient
    {
        private readonly EsgCompanyReportParameters _parameters;

        private readonly string _requestUri;

        private readonly JsonMediaTypeFormatter _jsonMediaTypeFormatter = new JsonMediaTypeFormatter
        {
            SerializerSettings = { ContractResolver = new CamelCasePropertyNamesContractResolver() }
        };

        public ESGCompanyReportClient(Uri uri, EsgCompanyReportParameters parameters, AuthenticationTicket ticket)
        {
            this._parameters = parameters;
            this._requestUri = string.Format("{0}/company/{1}/esgCompanyReport", uri, parameters.CompanyId);
            var ticketDataFormat = new CustomAccessTokenFormat();
            var accessToken = ticketDataFormat.Protect(ticket);
            this.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            this.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
        }

        public async Task<HttpResponseMessage> PostAsync()
        {
            return await this.PostAsync(this._requestUri, this._parameters, this._jsonMediaTypeFormatter).ConfigureAwait(false);
        }

        public async Task<PdfReportExecutionResult> GetResponseMessageAsync(HttpResponseMessage message)
        {
            return
                await message.Content.ReadAsAsync<PdfReportExecutionResult>(new[] { this._jsonMediaTypeFormatter }).ConfigureAwait(false);
        }

        public async Task<EsgRatingsError> GetErrorMessageAsync(HttpResponseMessage message)
        {
            return
                await message.Content.ReadAsAsync<EsgRatingsError>(new[] { this._jsonMediaTypeFormatter }).ConfigureAwait(false);
        }
    }
}
